package com.zygame.sdk.view.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.zygame.sdk.CmCode;
import com.zygame.sdk.ZyGameSDK;
import com.zygame.sdk.adapter.OptionsAdapter;
import com.zygame.sdk.bean.UserBean;
import com.zygame.sdk.db.UserDao;
import com.zygame.sdk.model.UserModel;
import com.zygame.sdk.utils.LoginUtil;
import com.zygame.sdk.utils.http.HttpUtil;
import com.zygame.sdk.utils.http.NetHttpUtil.DataCallback;
import com.zygame.sdk.utils.log.LogHelper;
import com.zygame.sdk.utils.res.FYResource;
import com.zygame.sdk.utils.res.ResourceUtil;
import com.zygame.sdk.utils.toast.ToastUtil;
import com.zygame.sdk.view.ImageEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Yuxl
 * 登录弹窗
 */

public class ZY_Dialog_Login extends ZY_BaseDialog {

    private Context mContext;

    protected final String TAG = "LoginDialog";

    private PopupWindow selectPopupWindow;
    private Handler handler;
    private ArrayList<Map<String, String>> datas = new ArrayList<Map<String, String>>();
    private ListView listView = null;
    private int pwidth;

    // 自定义Adapter
    private OptionsAdapter optionsAdapter = null;

    private ImageEditText et_account;
    private ImageEditText et_pwd;
    private ImageView fy_delete_account;
    private ImageView fy_delete_pwd;
    private Button btn_login;
    private Button btn_callcenter;
    private ImageView iv_select_account; // 下拉列表
    private LinearLayout ll_account_root;
    private TextView tv_forget_pwd;

    private String mAccount;
    private String mPwd;

    private View layout_top;

//	private int flag = 1;

    public ZY_Dialog_Login(Context context) {
        super(context);
        this.mContext = context;
    }

    @Override
    protected void init() {
        showSoft();
        showBack(true);
        et_account = (ImageEditText) findViewById(ResourceUtil.getId(mContext, "et_account"));
        et_pwd = (ImageEditText) findViewById(ResourceUtil.getId(mContext, "et_pwd"));

        et_account.setHintid("GSDK_username_placeholaer");
        et_account.setLineHide();
        et_account.setContentClole("#000000");
        et_account.hideDelete();

        et_pwd.setTextViewBG("fy_input_pwd");
        et_pwd.setHintid("GSDK_password_placeholaer");
        et_pwd.hidePromptGone();
        et_pwd.hideHidstoryImageView();
        et_pwd.setLineHide();
        et_pwd.setContentClole("#000000");
        et_pwd.setPwdInputType();
        et_pwd.setIcon(mContext.getResources().getDrawable(ResourceUtil.getDrawableId(mContext, "fy_pwd")));
        et_pwd.hideDelete();


        fy_delete_account = (ImageView) et_account.findViewById(ResourceUtil.getId(mContext, "fy_delete"));
        fy_delete_pwd = (ImageView) et_pwd.findViewById(ResourceUtil.getId(mContext, "fy_delete"));
        iv_select_account = (ImageView) et_account.findViewById(ResourceUtil.getId(mContext, "fy_ie_history"));

        btn_callcenter = (Button) findViewById(ResourceUtil.getId(mContext, "btn_callcenter"));

        btn_login = (Button) findViewById(ResourceUtil.getId(mContext, "btn_login"));
        ll_account_root = et_account.getRoot();
        tv_forget_pwd = (TextView) findViewById(ResourceUtil.getId(mContext, "tv_forget_pwd"));

        layout_top = (LinearLayout) findViewById(ResourceUtil.getId(mContext, "layout_top"));


        // 自动设置账号密码
        UserDao ud = new UserDao();
        UserBean ub = ud.queryBean();
        if (ub != null) {
            et_account.setContent(ub.userName);
            et_pwd.setContent(ub.pwd);
        }

        fy_delete_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_account.setContent("");
            }
        });
        fy_delete_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_pwd.setContent("");
            }
        });
        iv_select_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                initWedget(mContext);
                popupWindwShowing();
            }
        });
        et_account.hidePromptText();
//		tv_close.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_callcenter.setOnClickListener(this);
        btn_back.setOnClickListener(this);
        tv_forget_pwd.setOnClickListener(this);

    }

    @Override
    protected String getResourceStr() {
        return "zy_dialog_login";
    }


    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == ResourceUtil.getId(mContext, "tv_close")) {
            ZyGameSDK.getInstance().setDialogDismissFlag(CmCode.CODE_LOGIN_CANCEL);
            ZY_Dialog_Login.this.dismiss();
        } else if (id == ResourceUtil.getId(mContext, "btn_login")) {
            mAccount = et_account.getContent().trim();
            mPwd = et_pwd.getContent().trim();
            if (mAccount.isEmpty() || mPwd.isEmpty()) {
                ToastUtil.showToast(mContext, "密码账号不能为空");
                return;
            }
            showLoad(true);
            HttpUtil.login(mAccount, mPwd, "1", "1", "", mContext, onLoginCallback);
        } else if (id == ResourceUtil.getId(mContext, "btn_callcenter")) {
            String str = btn_callcenter.getText().toString().trim();
            String callNum = str.split(":")[1];
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + callNum));
            mContext.startActivity(intent);
        } else if (id == ResourceUtil.getId(mContext, "btn_back")) {
//			Game65SDK.getInstance().setDialogDismissFlag(0);
            /*if (UserModel.getInstance().getLogin_account() != null) {
				new AccountCenter(mContext).show();
			} else {
				new Register(mContext).show();
			}*/
//
             Zy_Dialog_main.getInstance(mContext).show();
            ZY_Dialog_Login.this.dismiss();
        } else if (id == ResourceUtil.getId(mContext, "tv_forget_pwd")) {//忘记密码
//			Game65SDK.getInstance().setDialogDismissFlag(_65Code.CODE_LOGIN_CANCEL);
            new ZY_Dialog_ForgetPwd(mContext).show();
            ZY_Dialog_Login.this.dismiss();
        }
    }

    DataCallback<JSONObject> onLoginCallback = new DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
            LogHelper.i("login接口", paramObject.toString());
            showLoad(false);
            String code = paramObject.optString("code");
//			et_account.hidePromptText();

            if (code.equals("0")) {
                LoginUtil.loginResult(mAccount, mPwd, paramObject, mContext,"1",1,"");
//				mContext.getSharedPreferences("tokeninfo", 0).edit().putString("login_token",paramObject.optString("login_token")).commit();
                ZyGameSDK.getInstance().onLoginResult(UserModel.getInstance());

                ZY_Dialog_Login.this.dismiss();
            } else {

//				ToastUtil.showToast(mContext,paramObject.optString("message"));
                et_account.setPromptText(paramObject.optString("message"));
            }
        }

        @Override
        public void callbackError(String error) {
//            ZyGameSDK.getInstance().onResult(CmCode.CODE_LOGIN_FAIL, "65 sdk login fail !");
        }

    };

    /**
     * 显示PopupWindow窗口
     *
     * @param popupwindow
     */
    public void popupWindwShowing() {
        // 将selectPopupWindow作为parent的下拉框显示，并指定selectPopupWindow在Y方向上向上偏移3pix，
        // 这是为了防止下拉框与文本框之间产生缝隙，影响界面美化
        // （是否会产生缝隙，及产生缝隙的大小，可能会根据机型、Android系统版本不同而异吧，不太清楚）
//		selectPopupWindow.showAsDropDown(ll_account_root, 0, -3);
        selectPopupWindow.showAsDropDown(ll_account_root, 0, 1);
    }

    /**
     * 初始化填充Adapter所用List数据
     */
    private void initDatas() {
        datas.clear();
        UserDao dao = new UserDao();
        List<UserBean> list = dao.queryList();
        for (UserBean userBean : list) {
            Map<String, String> map = new HashMap<String, String>();
            map.put(userBean.userName, userBean.pwd);
            datas.add(map);
        }
    }

    /**
     * 初始化PopupWindow
     */
    private void initPopuWindow(Context context) {
        initDatas();
        // PopupWindow浮动下拉框布局
        View loginwindow = LayoutInflater.from(context).inflate(ResourceUtil.getLayoutId(context, FYResource.layout.fy_ly_options), null);
//		View loginwindow = (View) ((Activity) context).getLayoutInflater().inflate(ResourceUtil.getLayoutId(context, FYResource.layout.fy_ly_options), null);
        listView = (ListView) loginwindow.findViewById(ResourceUtil.getId(context, "list"));
        // 设置自定义Adapter
        optionsAdapter = new OptionsAdapter(context, handler, datas);
        listView.setAdapter(optionsAdapter);
        selectPopupWindow = new PopupWindow(loginwindow, pwidth, LayoutParams.WRAP_CONTENT, true);
        selectPopupWindow.setOutsideTouchable(true);
        // 这一句是为了实现弹出PopupWindow后，当点击屏幕其他部分及Back键时PopupWindow会消失，
        // 没有这一句则效果不能出来，但并不会影响背景
        selectPopupWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    /**
     * 初始化界面控件
     */
    private void initWedget(Context context) {
        handler = new Handler(new AccountCallBack());
        int width = ll_account_root.getWidth();
        pwidth = width;
        // 初始化PopupWindow
        initPopuWindow(context);
    }


    //
    public class AccountCallBack implements Callback {

        @Override
        public boolean handleMessage(Message message) {
            // TODO Auto-generated method stub
            Bundle data = message.getData();
            switch (message.what) {
                case 1:
                    // 用户名回显，下拉框消失
                    int selIndex = data.getInt("selIndex");
                    et_account.setContent(datas.get(selIndex).entrySet().iterator().next().getKey());
                    et_pwd.setContent(datas.get(selIndex).entrySet().iterator().next().getValue());
                    popDismiss();
                    break;
                case 2:
                    // 移除下拉项数据
                    final int delIndex = data.getInt("delIndex");
                    UserDao dao = new UserDao();
                    dao.del(datas.get(delIndex).entrySet().iterator().next().getKey());
                    datas.remove(delIndex);
                    // 刷新下拉列表
                    optionsAdapter.notifyDataSetChanged();
                    if (datas.size() == 0) {
                        popDismiss();
                    }
                    break;
            }
            return false;
        }
    }


    /**
     * PopupWindow消失
     */
    public void popDismiss() {
        if (selectPopupWindow != null && selectPopupWindow.isShowing()) {
            selectPopupWindow.dismiss();
        }
    }

//	@Override
//	public void onDismiss(DialogInterface arg0) {
//		Game65SDK.getInstance().setDialogDismissFlag(_65Code.CODE_LOGIN_CANCEL);
//		super.onDismiss(arg0);
//	}

}
